from datetime import datetime

from flask import Flask, jsonify, request
from flask_cors import CORS

import DataTypeEncapsulation
import sqlconnect

# 创建 Flask 应用实例
app = Flask(__name__)
CORS(app)


# 路由定义
@app.route('/api/select/account/all', methods=['GET'])
def select_all_account():
    # 从数据库中查询所有用户数据
    userdata = sqlconnect.sql_select_Account()
    # 将查询结果转换为 UserData 对象列表
    userdata_objects = [DataTypeEncapsulation.UserData(*row) for row in userdata]
    # 将 UserData 对象列表转换为字典列表
    userdata_dicts = [user.to_dict() for user in userdata_objects]
    return jsonify(userdata_dicts)


@app.route('/api/select/account/by/<id>', methods=['GET'])
def select_account_by_account(id):
    # 从数据库中根据 ID 查询用户数据
    Uid = int(id)
    userdata = sqlconnect.sql_select_Account_by_id(Uid)
    if len(userdata) == 0:
        return jsonify({'message': 'error account or password'}), 200
    # 将查询结果转换为 UserData 对象列表
    userdata_objects = [DataTypeEncapsulation.UserData(*row) for row in userdata]
    # 将 UserData 对象列表转换为字典列表
    userdata_dicts = [user.to_dict() for user in userdata_objects]
    return jsonify({'data': userdata_dicts}), 200


@app.route('/api/select/money', methods=['GET'])
def select_money():
    Uid = request.args.get('id')
    if Uid is None:
        return jsonify({'message': 'error missing id'}), 200
    try:
        print(f"{datetime.now()} 用户id: {Uid} 查询资金")
        data = sqlconnect.sql_select_money_byId(int(Uid))
        if data == []:
            return jsonify({'message': 'id not exist'}), 200
        data = data[0]
        return jsonify({'message': '查询成功,ok', 'money': data[0]}), 200
    except Exception as e:
        print(e)
        return jsonify({'message': f'查询失败, 错误信息:{e}'}), 500


@app.route('/api/update/money', methods=['PUT'])
def update_money():
    money = request.args.get('money')
    account = request.args.get('account')
    if account is None or money is None:
        return jsonify({'message': 'error missing account or money'}), 200
    try:
        print(f"{datetime.now()} 用户: {account} 开始交易")
        data = sqlconnect.sql_select_Account_by_account(account)
        if data != []:
            data = sqlconnect.sql_update_money(account, int(money))
            data = data[0]
            return jsonify({'message': '操作成功,ok', 'money': data[0]}), 200
        else:
            return jsonify({'message': 'error account or password'}), 200
    except Exception as e:
        print(e)
        return jsonify({'message': f'更新失败, 错误信息:{e}'}), 500


@app.route('/api/update/password', methods=['POST'])
def update_password():
    account = request.args.get('account')
    new_password = request.args.get('new_password')
    password = request.args.get('password')
    if account is None or new_password is None or password is None:
        return jsonify({'message': 'error missing account or new_password or password', 'data': False}), 200
    try:
        print(f"{datetime.now()} 用户: {account} 修改密码")
        Udata = sqlconnect.sql_Login_by_account(account, password)
        if Udata != []:
            sqlconnect.sql_update_password(account, new_password)
            return jsonify({'message': '更新成功', 'data': True}), 200
        else:
            return jsonify({'message': 'error account or password', 'data': False}), 200
    except Exception as e:
        print(e)
        return jsonify({'message': f'更新失败, 错误信息:{e}'}), 500


@app.route('/register', methods=['POST'])
def register():
    account = request.args.get('account')
    password = request.args.get('password')
    if account == '' or password == '' or account is None or password is None:
        return jsonify({'message': 'error missing account or password'}), 200
    try:
        print(f"{datetime.now()} 用户: {account} 开始注册")
        data = sqlconnect.sql_select_Account_by_account(account)
        if data:
            return jsonify({'message': '账号已存在'}), 200
        else:
            sqlconnect.sql_add_Account(account, password)
            return jsonify({'message': '注册成功'}), 200
    except Exception as e:
        print(e)
        return jsonify({'message': f'注册失败, 错误信息:{e}'}), 500


@app.route('/login', methods=['GET'])
def login():
    account = request.args.get('account')
    password = request.args.get('password')
    if account is None or password is None:
        return jsonify({'message': 'error missing account or password'}), 200
    print(f"{datetime.now()} 用户: {account} 登录")
    data = sqlconnect.sql_Login_by_account(account, password)
    if not data:
        return jsonify({'message': 'error account or password'}), 200
    data_Objects = [DataTypeEncapsulation.UserData(*x) for x in data]
    data_dicts = [Obj.to_dict() for Obj in data_Objects]
    return jsonify({'message': '登录成功,ok', 'data': data_dicts}), 200


@app.route('/api/transfer/money', methods=['PUT'])
def transfer_money():
    money = request.args.get('money')
    sender = request.args.get('sender')
    receiver = request.args.get('receiver')
    if money is None or sender is None or receiver is None:
        return jsonify({'message': 'error missing money or sender or receiver'}), 200
    try:
        print(f"{datetime.now()} 用户: {sender} 开始转账")
        Udata = sqlconnect.sql_select_Account_by_account(receiver)
        if Udata != []:
            data = sqlconnect.sql_account_trans(money=int(money), sender=sender, receiver=receiver)
            return jsonify({'message': '转账成功', 'money': data[0][0]}), 200
        else:
            return jsonify({'message': 'error receiver'}), 200
    except Exception as e:
        print(e)
        return jsonify({'message': f'更新失败, 错误信息:{e}'}), 500


@app.route('/delete/account', methods=['DELETE'])
def delete_account():
    Uid = request.args.get('id')
    password = request.args.get('password')
    if Uid is None or password is None:
        return jsonify({'message': 'error missing id or password'}), 200
    try:
        print(f"{datetime.now()} 用户id:{Uid} 尝试注销账户")
        data = sqlconnect.sql_verify_password(id=Uid, password=password)
        # print("delect", data)
        if data:
            sqlconnect.sql_delete_account(Uid)
            return jsonify({'message': '注销账户成功'}), 200
        else:
            return jsonify({'message': 'error account or password'}), 201
    except Exception as e:
        print(e)
        return jsonify({'message': f'删除失败, 错误信息:{e}'}), 500


@app.route('/api/verify/password', methods=['GET'])
def verify_password():
    Uid = request.args.get('id')
    password = request.args.get('password')
    if Uid is None or password is None:
        return jsonify({'message': 'error missing id or password', 'data': False}), 200
    print(f"{datetime.now()} 用户id:{Uid} 开始验证密码")
    data = sqlconnect.sql_verify_password(Uid,password=password)
    if not data:
        return jsonify({'message': 'error id', 'data': False}), 200
    elif data:
        return jsonify({'message': 'ok', 'data': True}), 200
    else:
        return jsonify({'message': 'error password', 'data': False}), 200


@app.route('/api/get/history', methods=['GET'])
def get_history():
    try:
        account = request.args.get('account')
        pagesize = request.args.get('pageSize')
        page_number = request.args.get('pageNumber')
        if account is None or pagesize is None or page_number is None:
            return jsonify({'message': 'error missing account or pageSize or pageNumber'}), 200
        print(f"{datetime.now()} 用户: {account} 开始查询交易记录")
        data = sqlconnect.sql_select_history_by_account(account, int(pagesize), int(page_number))
        # x：表示data中的每一个元素。*x：表示将解包（unpacking），即将x
        # 中的元素作为参数传递给TransactionHistory类的构造函数。
        # DataTypeEncapsulation.TransactionHistory(*x)：
        # 表示使用解包后的x来创建TransactionHistory类的实例。
        dataObjects = [DataTypeEncapsulation.TransactionHistory(*x) for x in data]
        data_dicts = [Obj.to_dict() for Obj in dataObjects]
        return jsonify({'message': f'ok', 'data': data_dicts,'count': len(data)}), 200
    except Exception as e:
        print(e)
        return jsonify({'message': f'获取失败, 错误信息:{e}'}), 500


# 启动 Flask 应用
if __name__ == '__main__':
    app.run(debug=True)
